package com.dayaokeji.rhythmschoolstudent.utils;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;

import com.dayaokeji.server_api.domain.UserInfo;
import com.orhanobut.logger.Logger;

import java.util.Random;
import java.util.Set;
import java.util.UUID;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by gordan on 2017/8/22.
 *
 * JPush 别名设置操作类
 */

public class JPushAliasUtils {

    private static JPushAliasUtils mInstance;

    private static int index = 0;

    private JPushAliasUtils(){}

    public static JPushAliasUtils getInstance() {
        if (null == mInstance) {
            synchronized (JPushAliasUtils.class) {
                if (null == mInstance) {
                    mInstance = new JPushAliasUtils();
                }
            }
        }
        return mInstance;
    }

    /**
     * 设置JPush alias
     */
    public void setJPushAlias(final Context context) {

        UserInfo userInfo = UserUtils.getUserInfo();
        if (null != userInfo && userInfo.getUniversityId() != 0 && !TextUtils.isEmpty(userInfo.getWorkNo())) {
            final StringBuilder builder = new StringBuilder();
            builder.append(userInfo.getUniversityId());
            builder.append(userInfo.getWorkNo());
            /**
             * 设置不成功就不停的尝试去设置alias
             */
            JPushInterface.setAlias(context, builder.toString(), new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    if (i != 0) {
                        if (index < 3) {
                            if (context != null) {
                                if (AndroidUtils.isAppOnForeground()) {
                                    setJPushAlias(context);
                                }
                            }
                        }
                        index ++;
                        Logger.d("set alias fail === "+builder.toString());
                    }else{
                        Logger.d("set alias success === "+builder.toString());
                    }
                }
            });

        }
    }

    /**
     * 设置别名回掉 , 如果设置失败，则尝试重新设置
     * @param pushMessage
     */
    public void onAliasOperatorResult(final Context context,JPushMessage pushMessage) {
        int errorCode = pushMessage.getErrorCode();
        //返回的错误码为6002 超时,6014 服务器繁忙,都建议延迟重试
        if(errorCode == 6002 || errorCode == 6014){
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    setJPushAlias(context);
                }
            },1000);
        }
    }

}
